package com.zhanbo.zhanbowymusic.music;



import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.AssetManager;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mwx.baselib.bean.SongBean;
import com.mwx.baselib.constant.Constant;
import com.mwx.baselib.net.AppConfig;
import com.mwx.baselib.utils.AssetsUtils;
import com.mwx.baselib.utils.MLog;
import com.mwx.baselib.utils.SDFileUtility;
import com.mwx.baselib.utils.SPUtils;
import com.zhanbo.zhanbowymusic.MyApplication;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 音乐播放器控制类
 */
public class MusicController {
    String  TAG ="MusicController";
    public static MusicController musicController;

    private Intent intent;

    //歌单中歌曲列表
    List<SongBean> songs = new ArrayList<>();

    //当前播放歌曲索引
    private int currentPosition;

    //musicService对象
    private MusicService musicService;

    //使用ServiceConnection来监听Service状态的变化
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            musicService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            //这里我们实例化audioService,通过binder来实现
            musicService = ((MusicService.AudioBinder) binder).getService();
        }
    };

    /**
     * 获取MusicController单例
     *
     * @return
     */
    public static MusicController getInstance() {
        if (musicController == null) {
            musicController = new MusicController();
        }
        return musicController;
    }

    /**
     * 构造方法中启动service服务
     */
    public MusicController() {
        startMusicService();
        EventBus.getDefault().register(this);
    }

    /**
     * 启动service
     */
    public void startMusicService() {
        intent = new Intent();
        intent.setClass(MyApplication.getAppContext(), MusicService.class);
        MyApplication.getAppContext().bindService(this.intent, conn, Context.BIND_AUTO_CREATE);
        MyApplication.getAppContext().startService(this.intent);
    }

    /**
     * 停止service
     */
    public void stopMusicService() {
        Log.e(TAG, "stopMusicService: MusicController");
        MyApplication.getAppContext().stopService(intent);
        MyApplication.getAppContext().unbindService(conn);
    }

    //播放标识
    public boolean isPlaying = false;

    //播放按钮选中标识
    public boolean isSelected = false;


    /**
     * 返回当前播放时间
     *
     * @return - 当前播放时间
     */
    public int getCurrentDuration() {
        return musicService.getCurrentDuration();
    }
    /**
     * 返回当前歌曲整体时长
     */
    public int getDuration() {
        return musicService.getDuration();
    }

    /**
     * 更新歌单数据 并播放 - 点击歌单歌曲列表页面的全部播放按钮调用此方法
     */
    public void updateAndPlaySheetData(List<SongBean> songs) {
        //将当前歌单信息更新
        this.songs.clear();
        this.songs.addAll(songs);
        //通知 MainActivity 的更新歌单数据，为pop列表准备数据 Event.id = 1
        EventBus.getDefault().post(new OnEvent(1));
        //播放全部歌曲，从索引 0  位置开始 即为第一首歌
        changeMusic(0);
        //更新初始播放状态
        isPlaying = true;
    }

    /**
     * 更新歌单数据 不播放 - 重现上次退出播放列表
     */
    public void updateSheetData(List<SongBean> songs) {
        //将当前歌单信息更新
        this.songs.clear();
        this.songs.addAll(songs);
        //通知 MainActivity 的更新歌单数据，为pop列表准备数据 Event.id = 1
        EventBus.getDefault().post(new OnEvent(1));
    }

    /**
     * 更新歌单数据 并播放 - 点击歌单歌曲列表页面的全部播放按钮调用此方法
     */
    public void updateAndPlaySheetData(List<SongBean> songs, int position) {
        //将当前歌单信息更新
        this.songs.clear();
        this.songs.addAll(songs);
        //通知 MainActivity 的更新歌单数据，为pop列表准备数据 Event.id = 1
        EventBus.getDefault().post(new OnEvent(1));
        //播放全部歌曲，从索引 0  位置开始 即为第一首歌
        currentPosition = position;
        changeMusic(currentPosition);
        //更新初始播放状态
        isPlaying = true;
    }

    /**
     * 获取当前歌单数据
     *
     * @return - 当前歌单list集合
     */
    public List<SongBean> getSheetData() {
        return songs;
    }

    /**
     * 更新一条歌曲进当前歌单 , 为搜索页面准备  收藏页
     *
     * @param song - 搜索页面单个播放对象
     */
    public void updateItemDate(SongBean song) {
        //歌曲是否存在标识，默认为false
        boolean isExist = false;
        //存在歌曲索引，临时变量
        int isExistPosition = -1;
        //判空，防止空指针
        if (songs != null && songs.size() > 0) {
            // 循环便利 当前songs集合
            for (int i  = 0 ; i < songs.size(); i++) {
                // 如果当前遍历对象的id != 参数id 添加进歌单
                if (song.getId() == songs.get(i).getId()) {
                    // 已存在，将当前播放索引 更改为目标歌曲索引
                    isExist = true;
                    isExistPosition = i;
                }
            }
        } else {
            //当前 播放列表为空，此为第一首，添加进歌单
            songs.add(song);
            isExist =true;
            currentPosition = 0;
        }

        //如果 isExist = true,证明歌曲存在播放列表中，将当前播放索引，改为目标索引
        if(isExist){
            currentPosition = isExistPosition;
        }else {
            // 如果 isExist = false,证明歌曲不存在播放列表中，则添加
            songs.add(currentPosition + 1, song);
            currentPosition = currentPosition + 1;
        }

        //通知 MainActivity 的更新歌单数据，为pop列表准备数据 Event.id = 1
        EventBus.getDefault().post(new OnEvent(1));
        changeMusic(currentPosition);
        /*
            将播放状态更新;
            避免第一次播放是在搜索直接添加播放歌曲，之后点击播放键重新走播放逻辑，
            isPlaying = false 的情况,从而导致播放列表的第一首
         */
        isPlaying = true;
    }

    /**
     * 更新索引 - 播放列表中点击指定歌曲播放使用
     *
     * @param position - 索引
     */
    public void updatePosition(int position) {
        currentPosition = position;
        changeMusic(currentPosition);
    }

    /**
     * 获取当前播放索引
     *
     * @return - 当前播放索引
     */
    public int getCurrentPosition() {
        return currentPosition;
    }

    /**
     * 更新当前播放索引 - 不播放
     */
    public void setCurrentPosition(int position) {
        currentPosition = position;
        //通知更新当前播放歌曲信息
        EventBus.getDefault().post(new OnEvent(3));
    }

    //播放模式标识
    public int currentMode = 0;

    /**
     * 播放模式选择
     *
     * @param mode - 播放模式
     *             0 - 列表循环
     *             1 - 随机播放
     *             2 - 单曲循环
     */
    public void changeMode(int mode) {
        currentMode = mode;
        EventBus.getDefault().post(new OnEvent(Constant.MUSIC_MODE));
    }

    public int getchangeMode(){
        return currentMode;
    }

    /**
     * 更换歌曲
     *
     * @param
     */
    public void changeMusic(int position) {
        //当前播放标识替换为传递过来的值
        currentPosition = position;
        //songs != null 并且有值，musicService已启动
        if (songs != null && songs.size() > 0) {
            if (musicService != null) {
                //预留，为启动加载本地准备
                if (position == -2) {
                    currentPosition = 0;
                } else {
                    // position = 0 为第一首歌点击上一首发生的情况，播放列表最后一首
                    if (position < 0) {
                        currentPosition = songs.size() - 1;
                        //position > songs.size - 1 ,为在最后一首歌点击下一首，默认播放列表第一首
                    } else if (position > songs.size() - 1) {
                        currentPosition = 0;
                    }
                }
                List<SongBean> recentlyPlayedList = new ArrayList<>();
                    String detail = "";
                    SDFileUtility sdHelper2 = new SDFileUtility(MyApplication.getAppContext());
                    try {
                        detail = sdHelper2.readFromSD(Constant.RECENTLY_PLAYED);
                        //添加到最近播放列表
                        if (!TextUtils.isEmpty(detail)){
                            recentlyPlayedList =  new Gson().fromJson(detail,new TypeToken<List<SongBean>>() {}.getType());
                            boolean isin =false;
                            for (SongBean songBean : recentlyPlayedList) {
                                if (songBean.getId()==songs.get(currentPosition).getId()){
                                    isin = true;
                                    break;
                                }
                            }
                            if (!isin){
                                recentlyPlayedList.add(songs.get(currentPosition));
                                String songStr = new Gson().toJson(recentlyPlayedList);
                                sdHelper2.savaFileToSD(Constant.RECENTLY_PLAYED,songStr);
                            }

                        }else {
                            recentlyPlayedList.add(songs.get(currentPosition));
                            String songStr = new Gson().toJson(recentlyPlayedList);
                            sdHelper2.savaFileToSD(Constant.RECENTLY_PLAYED,songStr);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "read contents from file has errors: " + e.getMessage(), e);
                    }






                //更新播放图标状态
                isSelected = true;
                isPlaying = true;
                MLog.i("当前歌曲地址："+AppConfig.URL+songs.get(currentPosition).getPlayUrl());
                //调取播放服务，传递url路径
                musicService.changeMusic(AppConfig.URL+songs.get(currentPosition).getPlayUrl());
                //通知更新当前播放歌曲信息
                EventBus.getDefault().post(new OnEvent(3));
                //更新进度条
                EventBus.getDefault().post(new OnEvent(5));
                //播放状态
                EventBus.getDefault().post(new OnEvent(Constant.MUSIC_PLAY));
                //更改pop中item状态
                EventBus.getDefault().post(new OnEvent(7));
            }
        }
    }

    /**
     * 继续
     */
    public void play() {
        isSelected = true;
        isPlaying = true;
        musicService.play();
        EventBus.getDefault().post(new OnEvent(Constant.MUSIC_PLAY));
    }

    /**
     * 暂停
     */
    public void pause() {
        isSelected = false;
        isPlaying=false;
        musicService.pause();
        EventBus.getDefault().post(new OnEvent(Constant.MUSIC_PAUSE));

    }

    /**
     * 下一曲
     */
    public void nextOne() {
        if (currentMode==0){
            changeMusic(++currentPosition);
        }
        if (currentMode == 1) {
            Random random = new Random();
            changeMusic(random.nextInt(songs.size()-1));
        }
        if (currentMode == 2) {
            changeMusic(currentPosition);
        }

    }

    /**
     * 上一曲
     */
    public void lastOne() {
        changeMusic(--currentPosition);
    }

    /**
     * 播放结束回调
     *
     * @param event - id = 0 播放完毕监听 自动调用下一曲
     */
    @Subscribe
    public void onCompletionEvent(OnEvent event) {
        if (event.id == 0) {
            if (currentMode==0){
                nextOne();
            }
            if (currentMode == 1) {
                Random random = new Random();
                changeMusic(random.nextInt(songs.size()-1));
            }
            if (currentMode == 2) {
                changeMusic(currentPosition);
            }
        }
    }

    /**
     * 进度跨进
     *
     * @param progress - 进度条时间
     */
    public void seekTo(int progress) {
        musicService.seekTo(progress);
    }

    public void destroyEvent() {
        EventBus.getDefault().unregister(this);
    }

}
